package com.aspire.boc.mms.wmf.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aspire.boc.mms.wmf.dao.wmf.WmfActionMapper;
import com.aspire.boc.mms.wmf.dao.wmf.WmfGroupRoleMapper;
import com.aspire.boc.mms.wmf.dao.wmf.WmfKeyMapper;
import com.aspire.boc.mms.wmf.dao.wmf.WmfResourceMapper;
import com.aspire.boc.mms.wmf.dao.wmf.WmfRoleActiondoMapper;
import com.aspire.boc.mms.wmf.dao.wmf.WmfRoleAuthMapper;
import com.aspire.boc.mms.wmf.dao.wmf.WmfRoleMapper;
import com.aspire.boc.mms.wmf.model.WmfAction;
import com.aspire.boc.mms.wmf.model.WmfActionExample;
import com.aspire.boc.mms.wmf.model.WmfActionExample.Criteria;
import com.aspire.boc.mms.wmf.model.WmfGroupRole;
import com.aspire.boc.mms.wmf.model.WmfGroupRoleExample;
import com.aspire.boc.mms.wmf.model.WmfResource;
import com.aspire.boc.mms.wmf.model.WmfResourceExample;
import com.aspire.boc.mms.wmf.model.WmfRole;
import com.aspire.boc.mms.wmf.model.WmfRoleActiondoExample;
import com.aspire.boc.mms.wmf.model.WmfRoleActiondoKey;
import com.aspire.boc.mms.wmf.model.WmfRoleAuth;
import com.aspire.boc.mms.wmf.model.WmfRoleAuthExample;
import com.aspire.boc.mms.wmf.model.WmfRoleExample;
import com.aspire.boc.mms.wmf.permission.PermissionCacheService;
import com.aspire.boc.mms.wmf.service.PermissionService;
import com.aspire.boc.mms.wmf.util.Configuration;
import com.aspire.boc.mms.wmf.util.Page;

@Service
public class PermissionServiceImpl implements PermissionService {
	private static Log log = LogFactory.getLog(PermissionServiceImpl.class);
	@Override
	public List<WmfAction> getAllActions() {
	    
	    WmfActionExample wmfActionExample = new WmfActionExample();
        com.aspire.boc.mms.wmf.model.WmfActionExample.Criteria criteria = wmfActionExample.createCriteria();
        // 只加载当前项目及基础框架action
	    String currentProjectName = Configuration.getConfiguration("system.current.project.name");
	    String frameworkProjectName = Configuration.getConfiguration("system.framework.project.name");
	    List<String> projectsNeedLoadResources = new ArrayList<String>(2);
	    if(StringUtils.isNotBlank(currentProjectName)) {
	    	projectsNeedLoadResources.add(StringUtils.trim(currentProjectName));
	    } 
	    if(StringUtils.isNotBlank(frameworkProjectName)) {
	    	projectsNeedLoadResources.add(StringUtils.trim(frameworkProjectName));
	    } 
	    if(!frameworkProjectName.isEmpty()) {
	    	criteria.andProjectNameIn(projectsNeedLoadResources);
	    }
        criteria.andStatusEqualTo((short) 1);
		return wmfActionMapper.selectByExample(wmfActionExample);
	}

	@Override
	public List<WmfAction> queryActionByRId(Integer resourceId) {
		WmfActionExample example = new WmfActionExample();
		 Criteria criteria = example.createCriteria();
		 criteria.andResourceIdEqualTo(resourceId).andStatusEqualTo((short) 1);
		 example.setOrderByClause("ORDERID");
		// 只加载当前项目及基础框架action
		    String currentProjectName = Configuration.getConfiguration("system.current.project.name");
		    String frameworkProjectName = Configuration.getConfiguration("system.framework.project.name");
		    List<String> projectsNeedLoadResources = new ArrayList<String>(2);
		    if(StringUtils.isNotBlank(currentProjectName)) {
		    	projectsNeedLoadResources.add(StringUtils.trim(currentProjectName));
		    } 
		    if(StringUtils.isNotBlank(frameworkProjectName)) {
		    	projectsNeedLoadResources.add(StringUtils.trim(frameworkProjectName));
		    } 
		    if(!frameworkProjectName.isEmpty()) {
		    	criteria.andProjectNameIn(projectsNeedLoadResources);
		    }
		return wmfActionMapper.selectByExample(example);
	}

	@Override
	public List<WmfRole> getWmfRolesByGId(String groupId) {
		WmfGroupRoleExample example1=new WmfGroupRoleExample();
		example1.createCriteria().andGroupidEqualTo(groupId);
		List<WmfGroupRole> groupRoles = wmfGroupRoleMapper.selectByExample(example1);
		
		List<String> values = new ArrayList<String>();
		for(WmfGroupRole groupRole :groupRoles){
			values.add(groupRole.getRoleId());
		}
		WmfRoleExample example = new WmfRoleExample();
		example.createCriteria().andIdIn(values);
		return wmfRoleMapper.selectByExample(example );
	}
	 
	@Override
	public List<WmfRole> getWmfRolesByGId(List<String> groupIds) {
		try{
			WmfGroupRoleExample wmfGroupRoleExample =new WmfGroupRoleExample();
			wmfGroupRoleExample.createCriteria().andGroupidIn(groupIds);
			List<WmfGroupRole> groupRoles = wmfGroupRoleMapper.selectByExample(wmfGroupRoleExample);
			if(groupRoles == null || groupRoles.size() == 0) {
			    return null;
			}
			List<String> values = new ArrayList<String>();
			for(WmfGroupRole groupRole :groupRoles){
				if(!values.contains(groupRole.getRoleId())){
					values.add(groupRole.getRoleId());
				}
			}
			WmfRoleExample example = new WmfRoleExample();
			example.createCriteria().andIdIn(values);
			return wmfRoleMapper.selectByExample(example);
		}catch(Exception exception){
			log.error(">>>>>>>  getWmfRolesByGId error: return null ." + exception);
			exception.printStackTrace();
			return null;
		}
		
	}

	@Override
	public List<WmfResource> getRouserceByRole(List<String> roleIds) {
		WmfRoleAuthExample example = new WmfRoleAuthExample();
		example.createCriteria().andRoleIdIn(roleIds);
		List<WmfRoleAuth>  wmfRoleAuths = wmfRoleAuthMapper.selectByExample(example);
		
		//-------------
		List<Integer> actionIds = new ArrayList<Integer>();
		for(WmfRoleAuth wmfRoleAuth : wmfRoleAuths){
			actionIds.add(wmfRoleAuth.getActionId());
		}
		WmfActionExample wmfActionExample = new WmfActionExample();
		Criteria criteria = wmfActionExample.createCriteria();
		criteria.andIdIn(actionIds).andStatusEqualTo((short) 1);
		// 只加载当前项目及基础框架action
	    String currentProjectName = Configuration.getConfiguration("system.current.project.name");
	    String frameworkProjectName = Configuration.getConfiguration("system.framework.project.name");
	    List<String> projectsNeedLoadResources = new ArrayList<String>(2);
	    if(StringUtils.isNotBlank(currentProjectName)) {
	    	projectsNeedLoadResources.add(StringUtils.trim(currentProjectName));
	    } 
	    if(StringUtils.isNotBlank(frameworkProjectName)) {
	    	projectsNeedLoadResources.add(StringUtils.trim(frameworkProjectName));
	    } 
	    if(!frameworkProjectName.isEmpty()) {
	    	criteria.andProjectNameIn(projectsNeedLoadResources);
	    }
		List<WmfAction> actions = wmfActionMapper.selectByExample(wmfActionExample);
		//-----
		List<Integer> resourceIds = new ArrayList<Integer>();
		for(WmfAction wmfAction : actions){
			resourceIds.add(wmfAction.getResourceId());
		}
		WmfResourceExample rexample = new WmfResourceExample();
		rexample.createCriteria().andIdIn(resourceIds ).andStatusEqualTo((short) 1);
		 example.setOrderByClause("ID");
		return resourceMapper.selectByExample(rexample  );
	}
	
	@Override
	public List<WmfAction> getActionsByRR(Integer resourceId, String roleId) {
		WmfRoleAuthExample example = new WmfRoleAuthExample();
		example.createCriteria().andRoleIdEqualTo(roleId);
		List<WmfRoleAuth>  wmfRoleAuths = wmfRoleAuthMapper.selectByExample(example);
		List<Integer> actionIds = new ArrayList<Integer>();
		for(WmfRoleAuth wmfRoleAuth : wmfRoleAuths){
			actionIds.add(wmfRoleAuth.getActionId());
		}
		
		WmfActionExample wmfActionExample = new WmfActionExample();
		Criteria criteria = wmfActionExample.createCriteria();
		criteria.andResourceIdEqualTo(resourceId).andIdIn(actionIds).andStatusEqualTo((short) 1);
		// 只加载当前项目及基础框架action
	    String currentProjectName = Configuration.getConfiguration("system.current.project.name");
	    String frameworkProjectName = Configuration.getConfiguration("system.framework.project.name");
	    List<String> projectsNeedLoadResources = new ArrayList<String>(2);
	    if(StringUtils.isNotBlank(currentProjectName)) {
	    	projectsNeedLoadResources.add(StringUtils.trim(currentProjectName));
	    } 
	    if(StringUtils.isNotBlank(frameworkProjectName)) {
	    	projectsNeedLoadResources.add(StringUtils.trim(frameworkProjectName));
	    } 
	    if(!frameworkProjectName.isEmpty()) {
	    	criteria.andProjectNameIn(projectsNeedLoadResources);
	    }
		return wmfActionMapper.selectByExample(wmfActionExample);
	}
	
	@Override
	public List<Integer> getActionsByRole(List<String> roleIds) {
	    WmfRoleAuthExample wmfRoleAuthExample = new WmfRoleAuthExample();
	    wmfRoleAuthExample.createCriteria().andRoleIdIn(roleIds);
	    List<WmfRoleAuth> wmfRoleAuths = wmfRoleAuthMapper.selectByExample(wmfRoleAuthExample);
	    List<Integer> result = new ArrayList<Integer>();
	    for(WmfRoleAuth wmfRoleAuth : wmfRoleAuths){
	    	if(!result.contains(wmfRoleAuth.getActionId())){
	    		result.add(wmfRoleAuth.getActionId());
	    	}
	    }
		return result;
	}
	
	@Override
	public List<WmfRole> getRolesPage(String clickGroupId,int start,int limit){
		if(null ==clickGroupId || "".equals(clickGroupId)){
			//获取角色
			WmfRoleExample wmfRoleExample = new WmfRoleExample();
			Page page = new Page(start,limit);
			wmfRoleExample.setPage(page);
			return wmfRoleMapper.selectByExample(wmfRoleExample);
		}else{
			//获取组对应的角色集合
			List<String> groupIdsList = new ArrayList<String>();
			for(String groupId : clickGroupId.split(",")){
				groupIdsList.add(groupId);
			}
			WmfGroupRoleExample wmfGroupRoleExample = new WmfGroupRoleExample();
			wmfGroupRoleExample.createCriteria().andGroupidIn(groupIdsList);
			List<WmfGroupRole> wmfGroupRoles = wmfGroupRoleMapper.selectByExample(wmfGroupRoleExample);
			if (wmfGroupRoles==null || wmfGroupRoles.size() ==0) {
				return new ArrayList<WmfRole>() ;
			}
			List<String> rolesList = new ArrayList<String>();
			for(WmfGroupRole wmfGroupRole : wmfGroupRoles){
				rolesList.add(wmfGroupRole.getRoleId());
			}
			//获取角色
			WmfRoleExample wmfRoleExample = new WmfRoleExample();
			wmfRoleExample.createCriteria().andIdIn(rolesList);
			Page page = new Page(start,limit);
			wmfRoleExample.setPage(page);
			return wmfRoleMapper.selectByExample(wmfRoleExample);
		}
	}
	
	@Override
	public int insertWmfRole(WmfRole wmfRole) {
		Integer key = wmfKeyMapper.getNextRoleID();
		wmfRole.setId(String.valueOf(key));
		wmfRoleMapper.insert(wmfRole);
		return key;
	}
	
	@Override
	@Transactional
	public void deleteWmfRole(String ids) throws Exception{
		try {
			//删除组和角色关联
			List<String> idsList = Arrays.asList(ids.split(","));
			WmfGroupRoleExample wmfGroupRoleExample = new WmfGroupRoleExample();
			wmfGroupRoleExample.createCriteria().andRoleIdIn(idsList);
			wmfGroupRoleMapper.deleteByExample(wmfGroupRoleExample);
			//删除功能和角色关联
			WmfRoleAuthExample wmfRoleAuthExample = new WmfRoleAuthExample();
			wmfRoleAuthExample.createCriteria().andRoleIdIn(idsList);
			wmfRoleAuthMapper.deleteByExample(wmfRoleAuthExample);
			//删除角色
			WmfRoleExample wmfRoleExample = new WmfRoleExample();
			wmfRoleExample.createCriteria().andIdIn(idsList);
			wmfRoleMapper.deleteByExample(wmfRoleExample);
		}catch(Exception e){
			log.error(">>>>>>>  deleteWmfRole error: " + e);
			e.printStackTrace();
			throw e;
		}
	}
	
	@Override
	@Transactional
	public int updateWmfRole(WmfRole _wmfRole){
		WmfRole  wmfRole = wmfRoleMapper.selectByPrimaryKey(_wmfRole.getId());
		if(null == wmfRole){
			return 0;
		}
		wmfRole.setEnname(_wmfRole.getEnname());
		wmfRole.setName(_wmfRole.getName());
		wmfRole.setStatus(_wmfRole.getStatus());
		wmfRole.setMemo(_wmfRole.getMemo());
		return wmfRoleMapper.updateByPrimaryKey(wmfRole);
	}
	
	@Override
	@Transactional
	public void updateRoleAuth(Map<String, Object> authMap,String roleId,String resourceid) throws Exception {
		try {
			//delete wmfRoleAuth 删除资源下所有可分配按钮（1，2）,新增action要重启
			WmfRoleAuthExample wmfRoleAuthExample = new WmfRoleAuthExample();
			List<WmfAction> actions = permissionCacheService.getActionsResourceId(new Integer(resourceid),"1,2");
			List<Integer> values = new ArrayList<Integer>();
			for(WmfAction wmfAction : actions){
				values.add(wmfAction.getId());
			}
			wmfRoleAuthExample.createCriteria().andActionIdIn(values).andRoleIdEqualTo(roleId);
			wmfRoleAuthMapper.deleteByExample(wmfRoleAuthExample);
			//insert wmfRoleAuth
			for(String authKey : authMap.keySet()){
				@SuppressWarnings("unchecked")
                List<String> authList = (List<String>) authMap.get(authKey);
				for(String auth : authList){
					WmfRoleAuth wmfRoleAuth = new WmfRoleAuth();
					wmfRoleAuth.setActionId(Integer.parseInt(auth));
					wmfRoleAuth.setRoleId(String.valueOf(roleId));
					wmfRoleAuth.setOwnertype(Short.valueOf("2"));
					wmfRoleAuth.setId(wmfKeyMapper.getNextRoleAuthID());
					wmfRoleAuthMapper.insert(wmfRoleAuth);
				}
			}
		} catch (Exception e) {
			log.error(">>>>>>>  updateRoleAuth error: " + e);
			e.printStackTrace();
			throw e;
		}
	}
	
	@Override
	public List<WmfRoleAuth> getActionAuth(List<WmfAction> actions) {
		List<WmfRoleAuth> wmfRoleAuths = new ArrayList<WmfRoleAuth>();
		if(null ==actions||actions.size()<=0){
			
		}else{
			List<Integer> values = new ArrayList<Integer>();
			for(WmfAction wmfAction : actions){
				values.add(wmfAction.getId());
			}
			
			WmfRoleAuthExample wmfRoleAuthExample = new WmfRoleAuthExample();
			wmfRoleAuthExample.createCriteria().andActionIdIn(values );
			wmfRoleAuths = wmfRoleAuthMapper.selectByExample(wmfRoleAuthExample);
		}
		return wmfRoleAuths;
	}
	
	/**
	 * 已经存在的话就直接返回成功
	 */
	@Override
	public int insertGroupRole(String groupid, String roleid) {
		try{
			WmfGroupRoleExample wmfGroupRoleExample = new WmfGroupRoleExample();
			wmfGroupRoleExample.createCriteria().andGroupidEqualTo(groupid).andRoleIdEqualTo(roleid);
			List<WmfGroupRole> wmfGroupRoles = wmfGroupRoleMapper.selectByExample(wmfGroupRoleExample);
			if(wmfGroupRoles!=null && wmfGroupRoles.size()>0){
				return 1;
			}
			Integer id = wmfKeyMapper.getNextGroupRoleID();
			WmfGroupRole wmfGroupRole = new WmfGroupRole();
			wmfGroupRole.setGroupid(groupid);
			wmfGroupRole.setRoleId(roleid);
			wmfGroupRole.setId(String.valueOf(id));
			wmfGroupRoleMapper.insert(wmfGroupRole);
			return id;
		}catch(Exception exception){
			exception.printStackTrace();
			return 0;
		}
	}
	
	@Override
	public void deleteWmfGroupRole(String ids) throws Exception {
		try {
			//删除组和角色关联
			List<String> idsList = Arrays.asList(ids.split(","));
			WmfGroupRoleExample wmfGroupRoleExample = new WmfGroupRoleExample();
			wmfGroupRoleExample.createCriteria().andRoleIdIn(idsList);
			wmfGroupRoleMapper.deleteByExample(wmfGroupRoleExample);
		}catch(Exception e){
			log.error(">>>>>>>  deleteWmfGroupRole error: " + e);
			e.printStackTrace();
			throw e;
		}
	}
	
	@Override
	public void deleteWmfGroupRole(String groupId, List<String> roleIds) throws Exception {

		WmfGroupRoleExample example = new WmfGroupRoleExample();
		example.createCriteria().andGroupidEqualTo(groupId).andRoleIdIn(roleIds);
		wmfGroupRoleMapper.deleteByExample(example);
	}

	@Override
	public WmfRole getAdminLevel1() {
		WmfRoleExample wmfRoleExample = new WmfRoleExample();
		wmfRoleExample.createCriteria().andEnnameEqualTo("adminlevel1");
		return wmfRoleMapper.selectByExample(wmfRoleExample).get(0);
	}
	
	@Override
	public long getRolesCount(String clickGroupId) {
		if(null ==clickGroupId || "".equals(clickGroupId)){
			//获取角色
			return wmfRoleMapper.countByExample(null);
		}else{
			//获取组对应的角色集合
			List<String> groupIdsList = new ArrayList<String>();
			for(String groupId : clickGroupId.split(",")){
				groupIdsList.add(groupId);
			}
			WmfGroupRoleExample wmfGroupRoleExample = new WmfGroupRoleExample();
			wmfGroupRoleExample.createCriteria().andGroupidIn(groupIdsList);
			List<WmfGroupRole> wmfGroupRoles = wmfGroupRoleMapper.selectByExample(wmfGroupRoleExample);
			if (wmfGroupRoles==null || wmfGroupRoles.size() ==0) {
				return 0 ;
			}
			List<String> rolesList = new ArrayList<String>();
			for(WmfGroupRole wmfGroupRole : wmfGroupRoles){
				rolesList.add(wmfGroupRole.getRoleId());
			}
			//获取角色
			WmfRoleExample wmfRoleExample = new WmfRoleExample();
			wmfRoleExample.createCriteria().andIdIn(rolesList);
			return wmfRoleMapper.countByExample(wmfRoleExample);
		}
	}
	
	@Override
    public HashSet<String> getUserActiondos(List<String> roleIds) {

	    WmfRoleActiondoExample example = new WmfRoleActiondoExample();
	    example.createCriteria().andRoleIdIn(roleIds);
	    List<WmfRoleActiondoKey> actiondoList = wmfRoleActiondoMapper.selectByExample(example);
	    int actiondosSize = 0;
	    if(actiondoList!=null && (actiondosSize=actiondoList.size())>0) {
	        HashSet<String> actiondos = new HashSet<String>(actiondosSize);
	        for(int i=0; i<actiondosSize; i++) {
	            String actionDo = actiondoList.get(i).getActionDo();
	            if(!actiondos.contains(actionDo)) {
	                actiondos.add(actionDo);
	            }
	        }
	        return actiondos;
	    }
	    return null;
    }
	
	@Override
	public List<Integer> getRoleAuthorizedGroupIds() {
		
		List<WmfGroupRole> groupRoles = wmfGroupRoleMapper.selectByExample(null);
		List<Integer> authorizedGroupIds = null;
		if(groupRoles != null && !groupRoles.isEmpty()) {
			authorizedGroupIds = new ArrayList<Integer>();
			for(WmfGroupRole gr : groupRoles) {
				Integer groupId = Integer.valueOf(gr.getGroupid());
				if(!authorizedGroupIds.contains(groupId)) {
					authorizedGroupIds.add(groupId);
				}
			}
		}
		return authorizedGroupIds;
	}
	
	@Autowired
	private WmfResourceMapper resourceMapper;
	@Autowired
	private WmfActionMapper wmfActionMapper;
	@Autowired
	private WmfRoleAuthMapper wmfRoleAuthMapper;
	@Autowired
	private WmfRoleMapper wmfRoleMapper;
	@Autowired
	private WmfGroupRoleMapper wmfGroupRoleMapper;
	@Autowired
	private WmfKeyMapper wmfKeyMapper;
	@Autowired
	private PermissionCacheService permissionCacheService;
	@Autowired
    private WmfRoleActiondoMapper wmfRoleActiondoMapper;
}
